package com.aaa.security;

import com.aaa.entity.Emp;
import com.aaa.entity.ResponseMsg;
import com.aaa.jwt.JwtTokenUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证成功处理器：登录成功
 */
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        /*Emp principal = (Emp) authentication.getPrincipal();
        System.out.println(principal);*/

        // 响应设置
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-Type","application/json");
        httpServletResponse.setStatus(200);

        String token = JwtTokenUtils.getToken(authentication);
        Emp principal = (Emp) authentication.getPrincipal();

        Map<String,Object> map = new HashMap<>();
        // 令牌
        map.put("token",token);
        // 用户信息：用户名，id，角色id
        map.put("principal",principal);

        ResponseMsg msg = new ResponseMsg();
        msg.setCode(200);
        msg.setMsg("认证成功");
        msg.setData(map);

        // 写：字符输出流
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSONObject.toJSONString(msg));
        writer.flush();
        writer.close();
    }
}
